package com.example.za.account.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.za.account.R;
import com.example.za.account.activity.ItemActivity;
import com.example.za.account.activity.RecordActivity;
import com.example.za.account.application.AccountApplication;
import com.example.za.account.dao.ExpenseDao;
import com.example.za.account.dao.IncomeDao;
import com.example.za.account.utils.Constant;
import com.example.za.account.utils.DateUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class HomeFragment extends BaseFragment {

    @BindView(R.id.text_detail_income)
    TextView textDetailIncome;
    @BindView(R.id.text_detail_expense)
    TextView textDetailExpense;
    @BindView(R.id.text_detail_balance)
    TextView textDetailBalance;
    @BindView(R.id.text_today_income)
    TextView textTodayIncome;
    @BindView(R.id.text_today_expense)
    TextView textTodayExpense;
    @BindView(R.id.text_week_income)
    TextView textWeekIncome;
    @BindView(R.id.text_week_expense)
    TextView textWeekExpense;
    @BindView(R.id.text_month_income)
    TextView textMonthIncome;
    @BindView(R.id.text_month_expense)
    TextView textMonthExpense;
    Unbinder unbinder;
    private View rootView;
    private IncomeDao incomeDao;
    private ExpenseDao expenseDao;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = super.onCreateView(inflater, container, savedInstanceState);
            unbinder = ButterKnife.bind(this, rootView);
            incomeDao = new IncomeDao(getContext());
            expenseDao = new ExpenseDao(getContext());
            updateToday();
            updateWeek();
            updateMonth();

        }

        // 缓存的rootView需要判断是否已经被加过parent，如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }

        return rootView;
    }

    public void updateToday() {
        Date start = DateUtils.getTodayStart();
        Date end = DateUtils.getTodayEnd();
        float incomes = incomeDao.getPeriodSumIncome(start, end, AccountApplication.sUser.getmId());
        textTodayIncome.setText(String.valueOf(incomes));
        float expenses = expenseDao.getPeriodSumExpense(start, end, AccountApplication.sUser.getmId());
        textTodayExpense.setText(String.valueOf(expenses));
    }

    private void updateWeek() {
        Date start = DateUtils.getWeekStart();
        Date end = DateUtils.getWeekEnd();
        float incomes = incomeDao.getPeriodSumIncome(start, end, AccountApplication.sUser.getmId());
        textWeekIncome.setText(String.valueOf(incomes));
        float expenses = expenseDao.getPeriodSumExpense(start, end, AccountApplication.sUser.getmId());
        textWeekExpense.setText(String.valueOf(expenses));
    }

    private void updateMonth() {
        Date start = DateUtils.getMonthStart();
        Date end = DateUtils.getMonthEnd();
        float incomes = incomeDao.getPeriodSumIncome(start, end, AccountApplication.sUser.getmId());
        textMonthIncome.setText(String.valueOf(incomes));
        textDetailIncome.setText(String.valueOf(incomes));
        float expenses = expenseDao.getPeriodSumExpense(start, end, AccountApplication.sUser.getmId());
        textMonthExpense.setText(String.valueOf(expenses));
        textDetailExpense.setText(String.valueOf(expenses));
        float balance = incomes - expenses;
        textDetailBalance.setText(String.valueOf(balance));
    }

    @Override
    protected Fragment getSubFragment() {
        return this;
    }

    @Override
    protected int getResId() {
        return R.layout.fragment_home;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshUI(String message) {
        if (TextUtils.equals(message, "income_inserted") || TextUtils.equals(message, "expense_inserted")
                || TextUtils.equals(message, "income_updated") || TextUtils.equals(message, "expense_updated")
                || TextUtils.equals(message, "income_deleted") || TextUtils.equals(message, "expense_deleted")
                || TextUtils.equals(message, "invest_inserted")) {
            updateToday();
            updateWeek();
            updateMonth();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    @OnClick({R.id.btn_record, R.id.ll_detail_today, R.id.ll_detail_week, R.id.ll_detail_month})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_record: {
                startActivity(new Intent(getActivity(), RecordActivity.class));
            }
            break;
            case R.id.ll_detail_today: {
                Intent intent = new Intent(getActivity(), ItemActivity.class);
                intent.putExtra(Constant.TYPE_DATE, Constant.TYPE_TODAY);
                startActivity(intent);
            }
            break;
            case R.id.ll_detail_week: {
                Intent intent = new Intent(getActivity(), ItemActivity.class);
                intent.putExtra(Constant.TYPE_DATE, Constant.TYPE_WEEK);
                startActivity(intent);
            }
            break;
            case R.id.ll_detail_month: {
                Intent intent = new Intent(getActivity(), ItemActivity.class);
                intent.putExtra(Constant.TYPE_DATE, Constant.TYPE_MONTH);
                startActivity(intent);
            }
            break;
        }
    }


}
